#!/bin/bash

#  准备三台虚拟机 配好yum、IP（能互相ping通）、关闭防火墙、selinux#  注意！！ 以下IP请以自己的为准

#  提示！！
#  会在首次执行脚本时创建密钥对输入一次密码  后续执行将不再输入密码

#  配置免密登陆
web1=192.168.88.10
web2=192.168.88.100
ti1=10
ti2=100
id_rsa_pub="$(ls ~/.ssh/ | awk '/id_rsa.pub/{print}')"
if [ ! -z $id_rsa_pub ];then
ssh-copy-id root@$web1 2> /dev/null
ssh-copy-id root@$web2 2> /dev/null   #  给另一台机器也传公钥
else
echo -e "\033[32m生成密钥对一路回车即可！！\033[0m"
sleep 1
ssh-keygen  #  生成密钥对 
ssh-copy-id root@$web1 2> /dev/null
ssh-copy-id root@$web2 2> /dev/null
fi
#  测试是否免密
ssh root@$web1 "exit" && ssh root@$web2 "exit"
if test `echo $?` -ne 0;then
echo -e "\033[31m请手动配置免密登陆！！\033[0m" && exit
fi

#  在另外两台机器安装网站服务httpd
ssh root@$web1 "yum -y install httpd; systemctl start httpd; exit" &> /dev/null\
&& ssh root@$web2 "yum -y install httpd; systemctl start httpd; exit" &> /dev/null
#  创建测试页面
ssh root@$web1 "echo 'web1~~' > /var/www/html/index.html; exit" && ssh root@$web2 "echo 'web2~~' > /var/www/html/index.html; exit"
#  测试结果
curl $web1 &> /dev/null && curl $web2 &> /dev/null
if [ `echo $?` != 0 ];then
echo -e "\033[31m请手动检查httpd服务是否正常启动！！\033[0m" && exit
fi

#  修改nginx配置文件
cd /usr/local/nginx
if [ `echo $?` != 0 ];then
echo -e "\033[31m请手动安装nginx并启动或把nginx目录放到/usr/local/下！！\033[0m" && exit
fi
\cp conf/nginx.conf.default conf/nginx.conf # 重置配置文件
sleep 0.5
sed -ir '34a upstream web {\
server '"${web1}"':80;\
server '"${web2}"':80;\
}' conf/nginx.conf
sed -i '47a proxy_pass http://web;'  conf/nginx.conf
ss -antulp | grep nginx &> /dev/null
if test $(echo $?) -eq 0;then
sbin/nginx -s reload  #  重新加载配置文件
else
sbin/nginx || killall `ss -antulp | grep 80 | awk -F\" 'NR==1{print $2}'` && sleep 1 && sbin/nginx  # 启动nginx
fi
for i in {1..6}
do
curl 127.0.0.1
done
echo -e "\033[32m=========================================================\033[0m"
echo -e "\033[32m这里可以看到web1和web2实现轮询出现就成功了！\033[0m"
